// ValidationAspects
// Written by Mike Saunders
// Released under Microsoft Public License (Ms-PL)
using System;
using System.Text.RegularExpressions;
using ValidationAspects.Exceptions;
using ValidationAspects.Sdk;

namespace ValidationAspects.Factories
{
	public class IsEmail : ValidatorFactoryBase<string>
	{
		public static Regex StrictRegex { get; set; }
		public static Regex LenientRegex { get; set; }

		public bool IsStrict { get; set; }

		static IsEmail()
		{
			ResetRegex();
		}

		public static void ResetRegex()
		{
			LenientRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
			StrictRegex = new Regex(@"^(([^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$");
		}

		#region Overrides of ValidatorFactoryBase<string>
		protected override Action<string, IValidationContext> ValidateAction
		{
			get
			{
				return (v, c) =>
				       {
				       	if (v == null)
				       		return;

				       	if (string.IsNullOrEmpty(v) || !(IsStrict ? StrictRegex.IsMatch(v) : LenientRegex.IsMatch(v))) throw new ValidateIsEmailException(v);
				       };
			}
		}
		#endregion
	}
}